package cn.wzptsoft.tinymallbe.service;

import cn.wzptsoft.common.exception.BizException;
import cn.wzptsoft.common.utils.MD5Utils;
import cn.wzptsoft.tinymallbe.entity.Theme;
import cn.wzptsoft.tinymallbe.entity.User;
import cn.wzptsoft.tinymallbe.entity.UserLoginDTO;
import cn.wzptsoft.tinymallbe.repository.ThemeRepository;
import cn.wzptsoft.tinymallbe.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;


    public User getUserById(Long id) {
        return userRepository.findFirstById(id);
    }

    public User login(UserLoginDTO userlogindot)
    {
        //使用传进来的用户对象判断
        User user= userRepository.findByUsername(userlogindot.getUsername());
//        如果没有这个用户
        if (user==null){
//            处理异常 抛出BizException异常
            throw new BizException("登录失败：账号或密码不正确");
        }
        /*
        * MD5Utils.md5Digest() 方法使用MD5算法对用户输入的密码进行加密，返回一个密文字符串。
        * userlogindot.getPassword() 是用户输入的原始密码，
        * user.getSalt() 是从数据库中读取的该用户的盐值（salt），
        * 将用户输入的密码和盐值一起进行加密，然后将加密后的字符串与数据库中存储的加密字符串比较
        * */
        String md5Password= MD5Utils.md5Digest(userlogindot.getPassword(),user.getSalt());
        if (!md5Password.equals(user.getPassword())){
            throw new BizException("登录失败：账号或密码不正确");
        }
        return user;


    }

    public User register(User user) {
        User byUsername = userRepository.findByUsername(user.getUsername());

        if (byUsername==null){
//          设置盐
            String salt="$1$"+user.getUsername();

            String md5Password= MD5Utils.md5Digest(user.getPassword(),salt);
            User user2 = new User();
            user2.setSalt(salt);
            user2.setUsername(user.getUsername());
            user2.setPassword(md5Password);
            user2.setNickname(user.getNickname());
            user2.setMobile(user.getMobile());
            userRepository.save(user2);
            return user2;
        }else {
            throw new BizException("注册失败：账号以被注册");
        }


    }

    public User info(String username) {
        User byUsername = userRepository.findByUsername(username);
        if (byUsername!=null){
            User user2 = new User();
            user2.setId(byUsername.getId());
            user2.setUsername(byUsername.getUsername());
            user2.setNickname(byUsername.getNickname());
            user2.setMobile(byUsername.getMobile());
            return user2;
        }else {
            return null;
        }

    }
}
